using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;
using JGSY.CMS.LowCode.Platform.Infrastructure.Services;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 多租户测试控制器
    /// 用于验证全局查询过滤器和租户隔离功能
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class MultiTenantTestController : ControllerBase
    {
        private readonly LowCodeDbContext _context;
        private readonly ITenantContext _tenantContext;
        private readonly ITenantService _tenantService;
        private readonly ILogger<MultiTenantTestController> _logger;

        public MultiTenantTestController(
            LowCodeDbContext context,
            ITenantContext tenantContext,
            ITenantService tenantService,
            ILogger<MultiTenantTestController> logger)
        {
            _context = context;
            _tenantContext = tenantContext;
            _tenantService = tenantService;
            _logger = logger;
        }

        /// <summary>
        /// 测试当前租户上下文
        /// </summary>
        [HttpGet("current-tenant")]
        public IActionResult GetCurrentTenant()
        {
            return Ok(new
            {
                TenantId = _tenantContext.TenantId,
                CurrentTenantId = _tenantContext.CurrentTenantId,
                HasTenant = _tenantContext.HasTenant,
                HttpContextTenantId = HttpContext.Items["TenantId"]?.ToString()
            });
        }

        /// <summary>
        /// 测试用户查询的租户过滤
        /// 验证全局查询过滤器是否正常工作
        /// </summary>
        [HttpGet("users")]
        public async Task<IActionResult> GetUsers()
        {
            try
            {
                // 这个查询会自动应用租户过滤器
                var users = await _context.Users
                    .Select(u => new
                    {
                        u.Id,
                        u.Username,
                        u.Email,
                        u.TenantId,
                        u.CreatedAt
                    })
                    .Take(10)
                    .ToListAsync();

                _logger.LogInformation($"查询到 {users.Count} 个用户，租户ID: {_tenantContext.TenantId}");

                return Ok(new
                {
                    CurrentTenant = _tenantContext.TenantId,
                    UserCount = users.Count,
                    Users = users,
                    QueryInfo = "此查询自动应用了租户过滤器"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询用户时发生错误");
                return StatusCode(500, new { error = ex.Message });
            }
        }

        /// <summary>
        /// 测试跨租户用户查询（忽略过滤器）
        /// 仅用于管理和测试场景
        /// </summary>
        [HttpGet("users/all")]
        public async Task<IActionResult> GetAllUsers()
        {
            try
            {
                // 忽略全局查询过滤器，查询所有租户的用户
                var allUsers = await _context.Users
                    .IgnoreQueryFilters() // 显式忽略租户过滤器
                    .Select(u => new
                    {
                        u.Id,
                        u.Username,
                        u.Email,
                        u.TenantId,
                        u.CreatedAt
                    })
                    .Take(20)
                    .ToListAsync();

                var tenantGroups = allUsers
                    .GroupBy(u => u.TenantId)
                    .Select(g => new
                    {
                        TenantId = g.Key,
                        UserCount = g.Count(),
                        Users = g.ToList()
                    })
                    .ToList();

                _logger.LogInformation($"跨租户查询到 {allUsers.Count} 个用户，涉及 {tenantGroups.Count} 个租户");

                return Ok(new
                {
                    CurrentTenant = _tenantContext.TenantId,
                    TotalUserCount = allUsers.Count,
                    TenantCount = tenantGroups.Count,
                    TenantGroups = tenantGroups,
                    QueryInfo = "此查询忽略了租户过滤器，显示所有租户数据"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "跨租户查询用户时发生错误");
                return StatusCode(500, new { error = ex.Message });
            }
        }

        /// <summary>
        /// 测试文章查询的租户过滤
        /// </summary>
        [HttpGet("articles")]
        public async Task<IActionResult> GetArticles()
        {
            try
            {
                var articles = await _context.Articles
                    .Select(a => new
                    {
                        a.Id,
                        a.Title,
                        a.TenantId,
                        a.Status,
                        a.CreatedAt
                    })
                    .Take(10)
                    .ToListAsync();

                return Ok(new
                {
                    CurrentTenant = _tenantContext.TenantId,
                    ArticleCount = articles.Count,
                    Articles = articles,
                    QueryInfo = "此查询自动应用了租户过滤器"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询文章时发生错误");
                return StatusCode(500, new { error = ex.Message });
            }
        }

        /// <summary>
        /// 测试租户服务功能
        /// </summary>
        [HttpGet("tenant-info")]
        public async Task<IActionResult> GetTenantInfo()
        {
            if (!_tenantContext.HasTenant)
            {
                return BadRequest("未设置租户上下文");
            }

            try
            {
                var tenant = await _tenantService.GetTenantByIdAsync(_tenantContext.TenantId!);
                
                if (tenant == null)
                {
                    return NotFound("租户不存在");
                }

                return Ok(new
                {
                    TenantInfo = tenant,
                    ContextTenantId = _tenantContext.TenantId,
                    ServiceInfo = "通过ITenantService获取租户信息"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取租户信息时发生错误");
                return StatusCode(500, new { error = ex.Message });
            }
        }

        /// <summary>
        /// 获取多租户系统统计信息
        /// </summary>
        [HttpGet("stats")]
        public async Task<IActionResult> GetMultiTenantStats()
        {
            try
            {
                // 当前租户数据统计
                var currentTenantUsers = await _context.Users.CountAsync();
                var currentTenantArticles = await _context.Articles.CountAsync();
                var currentTenantPermissions = await _context.Permissions.CountAsync();
                var currentTenantDepartments = await _context.Departments.CountAsync();
                var currentTenantTeams = await _context.Teams.CountAsync();
                var currentTenantWorkflows = await _context.Workflows.CountAsync();

                // 所有租户数据统计（忽略过滤器）
                var totalUsers = await _context.Users.IgnoreQueryFilters().CountAsync();
                var totalArticles = await _context.Articles.IgnoreQueryFilters().CountAsync();
                var totalPermissions = await _context.Permissions.IgnoreQueryFilters().CountAsync();
                var totalDepartments = await _context.Departments.IgnoreQueryFilters().CountAsync();
                var totalTeams = await _context.Teams.IgnoreQueryFilters().CountAsync();
                var totalWorkflows = await _context.Workflows.IgnoreQueryFilters().CountAsync();

                // 租户分布统计
                var usersByTenant = await _context.Users
                    .IgnoreQueryFilters()
                    .GroupBy(u => u.TenantId)
                    .Select(g => new { TenantId = g.Key, Count = g.Count() })
                    .ToListAsync();

                return Ok(new
                {
                    CurrentTenant = _tenantContext.TenantId,
                    CurrentTenantStats = new
                    {
                        Users = currentTenantUsers,
                        Articles = currentTenantArticles,
                        Permissions = currentTenantPermissions,
                        Departments = currentTenantDepartments,
                        Teams = currentTenantTeams,
                        Workflows = currentTenantWorkflows
                    },
                    GlobalStats = new
                    {
                        TotalUsers = totalUsers,
                        TotalArticles = totalArticles,
                        TotalPermissions = totalPermissions,
                        TotalDepartments = totalDepartments,
                        TotalTeams = totalTeams,
                        TotalWorkflows = totalWorkflows,
                        TenantCount = usersByTenant.Count,
                        UsersByTenant = usersByTenant
                    },
                    FilterInfo = "当前租户统计使用了全局过滤器，全局统计忽略了过滤器"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取多租户统计时发生错误");
                return StatusCode(500, new { error = ex.Message });
            }
        }

        /// <summary>
        /// 测试新转换实体的租户过滤
        /// </summary>
        [HttpGet("extended-entities")]
        public async Task<IActionResult> GetExtendedEntities()
        {
            try
            {
                // 测试权限实体的租户过滤
                var permissions = await _context.Permissions
                    .Select(p => new { p.Id, p.Name, p.Code, p.TenantId })
                    .Take(5)
                    .ToListAsync();

                // 测试部门实体的租户过滤
                var departments = await _context.Departments
                    .Select(d => new { d.Id, d.Name, d.TenantId })
                    .Take(5)
                    .ToListAsync();

                // 测试团队实体的租户过滤
                var teams = await _context.Teams
                    .Select(t => new { t.Id, t.Name, t.TenantId })
                    .Take(5)
                    .ToListAsync();

                // 测试工作流实体的租户过滤
                var workflows = await _context.Workflows
                    .Select(w => new { w.Id, w.Name, w.TenantId })
                    .Take(5)
                    .ToListAsync();

                return Ok(new
                {
                    CurrentTenant = _tenantContext.TenantId,
                    ExtendedEntitiesData = new
                    {
                        Permissions = new { Count = permissions.Count, Data = permissions },
                        Departments = new { Count = departments.Count, Data = departments },
                        Teams = new { Count = teams.Count, Data = teams },
                        Workflows = new { Count = workflows.Count, Data = workflows }
                    },
                    QueryInfo = "所有查询均自动应用了租户过滤器"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询扩展实体时发生错误");
                return StatusCode(500, new { error = ex.Message });
            }
        }
    }
}
